package com.ossfk.jt808.codec;

import com.ossfk.jt808.pojo.Jt808Msg;
import com.ossfk.jt808.utils.Jt808Utils;
import com.ossfk.net.utils.ByteHelper;
import com.ossfk.net.utils.HexStringUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class Jt808Encoder extends MessageToByteEncoder<Jt808Msg> {

	@Override
	protected void encode(ChannelHandlerContext ctx, Jt808Msg msg, ByteBuf out) throws Exception {
		byte[] body = null;
		try {
			body = encode4Msg(msg); // 将对象转换为byte
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(body!=null) {
			System.out.println("发送："+HexStringUtils.toHexString(body));
			out.writeBytes(body); // 消息体中包含我们要发送的数据
		}
	}

	/**
	 * 
	 * @Description: 消息编码
	 * @param message
	 * @return
	 * @throws Exception
	 * @author Liujiefu
	 * @date 2020-03-16 14:10:20
	 */
	public byte[] encode4Msg(Jt808Msg message) throws Exception {
		byte[] msgBodyBytes = message.getMsgBodyBytes();
		if (msgBodyBytes == null)
			msgBodyBytes = new byte[] {};
		// body默认不加密
		int msgBodyProps = Jt808Utils.generateMsgBodyProps(msgBodyBytes.length, 0, false, 0);
		// 生产消息头
		byte[] msgHeader = Jt808Utils.generateMsgHeader(message.getHeader().getTerminalPhone(),
				message.getHeader().getMsgId(), msgBodyBytes, msgBodyProps, message.getHeader().getFlowId());
		// 合并消息头和消息体
		byte[] headerAndBody = ByteHelper.concatAll(msgHeader, msgBodyBytes);
		// 生成校验码
		int checkSum = Jt808Utils.getCheckSum(headerAndBody, 0, headerAndBody.length);
		// 返回转义后的字节数组
		return Jt808Utils.doEscape(headerAndBody, checkSum);
	}
	
	
}
